<?php

defined('BASEPATH') or die('forbidden');

/**
 * 加载类
 * @author  Karson
 * @name    load.php
 * @since   2013-6-25 15:09:51
 */
class Load {

    function __construct() {
        
    }

    function config($name, $alias_name = null) {
        $name = strtolower($name);
        if (!$alias_name)
            $alias_name = $name;
        $controller = &get_instance('controller');
        if (isset($controller->config[$alias_name]))
            return true;
        if (empty($name))
            throw new Exception("配置文件[{$name}]名称不能为空");
        if (!preg_match('!^[a-zA-Z][a-zA-Z0-9_]+$!', $name))
            throw new Exception("配置[{$name}]包含有非法字符");
        $filename = APPPATH . 'configs/' . $name . '.php';
        if (!is_file($filename))
            throw new Exception("配置文件[{$name}]不存在");
        include $filename;
        if (is_array($config) && isset($config[$name])) {
            $controller->config[$alias_name] = $config[$name];
            unset($config);
        } else {
            throw new Exception("配置文件[{$name}]的值只能是一个数组");
        }
        unset($controller);
        log_message("Config[{$name}]");
        return true;
    }

    /**
     * 加载模型
     * @param string $name 模型名称
     * @param string $alias_name 模型别名，默认为null，为空时别名和模型名称相同
     * @param string $file_name 加载的文件名称，默认为null
     * @param mixed $args 构造函数的参数，默认为null
     * @return bool 加载成功返回true，失败返回false
     */
    function model($name, $alias_name = null, $file_name = null, $args = null) {
        $name = strtolower($name);
        if (!$alias_name)
            $alias_name = $name;
        $controller = & get_instance('controller');
        if (isset($controller->$alias_name))
            return true;
        if (!$file_name)
            $file_name = $name . '.php';
        if (empty($alias_name))
            throw new Exception("模型[{$alias_name}]名称不能为空");
        if (empty($alias_name))
            throw new Exception("模型[{$alias_name}]别名不能为空");
        if (!preg_match('!^[a-zA-Z][a-zA-Z0-9_]+$!', $alias_name))
            throw new Exception("模型[{$alias_name}]包含有非法字符");
        if (method_exists($this, $alias_name))
            throw new Exception("模型[{$alias_name}]已经被定义");
        $realfile = APPPATH . 'models/' . $file_name;
        if (!is_file($realfile))
            throw new Exception("模型[{$name}]文件不存在");
        include_once $realfile;
        $model_name = ucfirst($alias_name) . '_Model';
        $controller->$alias_name = new $model_name($args);
        if (method_exists($controller->$alias_name, '_init'))
            $controller->$alias_name->_init();
        foreach ($controller->models as $m => $n) {
            if (!property_exists($n, $alias_name)) {
                $n->$alias_name = & $controller->$alias_name;
            }
        }
        unset($controller);
        log_message("Model[{$model_name}]");
        return true;
    }

    /**
     * 加载类
     * @param string $name 类名称
     * @param string $alias_name 类别名，默认为null，为空时别名和类名称
     * @param string $file_name 加载的文件名称，默认为null
     * @param mixed $args 构造函数的参数，默认为null
     * @return bool 加载成功返回true，失败返回false
     */
    function library($name, $alias_name = null, $file_name = null, $args = null) {
        if (!$alias_name)
            $alias_name = $name;
        $controller = & get_instance('controller');
        if (isset($controller->$alias_name))
            return true;
        if (!$file_name)
            $file_name = strtolower($name) . '.php';
        if (empty($alias_name))
            throw new Exception("类库[{$name}]别名不能为空");
        if (!preg_match('!^[a-zA-Z][a-zA-Z0-9_]+$!', $alias_name))
            throw new Exception("类库[{$alias_name}]包含有非法字符");
        if (method_exists($this, $alias_name))
            throw new Exception("类库[{$alias_name}]已经被定义");
        $name = ucfirst($name);
        $controller->$alias_name = new $name($args);
        if (method_exists($controller->$alias_name, '_init'))
            $controller->$alias_name->_init();
        foreach ($controller->models as $m => $n) {
            if (!property_exists($n, $alias_name)) {
                $n->$alias_name = & $controller->$alias_name;
            }
        }
        unset($controller);
        log_message("Library[{$name}]");
        return true;
    }

    /**
     * 加载辅助函数脚本
     * @param string $name 脚本文件名称
     * @return string 成功时加载的函数库
     */
    function helper($name) {
        if (!preg_match('!^[a-zA-Z][a-zA-Z0-9_]+$!', $name))
            throw new Exception("辅助函数[{$name}]包含有非法字符");
        $file_name = $name . '.php';
        $file_path = BASEPATH . 'helpers/' . $file_name;
        if (!is_file($file_path)) {
            $file_path = APPPATH . 'helpers/' . $file_name;
            if (!is_file($file_path)) {
                throw new Exception("辅助函数[{$name}]未找到");
            }
        }
        include_once $file_path;
        log_message("Helper[{$name}]");
        return true;
    }

    /**
     * 加载数据库
     * @staticvar var $dbs 静态数据库
     * @param string $name 数据库名称，默认为null
     * @param string $alias_name 数据库别名，默认为null，为null时别名等于数据库名称
     * @return object 数据库对象
     */
    function database($name = null, $alias_name = null) {
        log_message("Database[{$name}]");
        if (!$alias_name)
            $alias_name = $name;
        $controller = & get_instance('controller');
        $controller->load->config($name);
        static $dbs = array();
        if ($name && isset($dbs[$name])) {
            $controller->$alias_name = $dbs[$name];
            return $dbs[$name];
        } else if ($name && isset($controller->config[$name]) && !empty($controller->config[$name]['library'])) {
            $dbs[$name] = new $controller->config[$name]['library']($controller->config[$name]);
            $controller->$alias_name = $dbs[$name];
            unset($controller);
            return $dbs[$name];
        }
    }

}
